package org.example.handler;


import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.ReferenceCountUtil;
import io.netty.util.concurrent.Promise;
import lombok.extern.slf4j.Slf4j;
import org.example.domain.po.RpcResponseMessagePO;
import org.example.utils.NettyClientUtils;

import java.util.Objects;

/**
 * @description: 接收结果处理器
 * @author: feixiang.li
 * @date: 2025-01-02 22:40
 */
@Slf4j
public class RpcResponseMessageHandler extends SimpleChannelInboundHandler<RpcResponseMessagePO> {
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, RpcResponseMessagePO rpcResponseMessagePO) throws Exception {
        log.error("消费者-收到dubbo响应消息:{}", rpcResponseMessagePO);
        try {
            Promise<Object> remove = NettyClientUtils.getPromises().remove(rpcResponseMessagePO.getSequenceId());
            if (Objects.nonNull(remove)) {
                Object returnValue = rpcResponseMessagePO.getReturnValue();
                Exception exceptionValue = rpcResponseMessagePO.getExceptionValue();
                if (exceptionValue != null) {
                    remove.setFailure(exceptionValue);
                } else {
                    remove.setSuccess(returnValue);
                }
            }
        } finally {
            ReferenceCountUtil.release(rpcResponseMessagePO);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.debug("出现异常", cause);
        ctx.close();
    }
}
